package com.xuhuan.juc.assist;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;

/**
 * @Author huan.xu
 * @Date 2021/12/29 16:29
 * @Description 有6个线程执行逻辑，主线程需要等待6个线程全部执行完成才执行接下来的逻辑。
 */
@Slf4j
public class CountDownLatchDemo {

    public static void main(String[] args) throws InterruptedException {
        countDownLatchExecBusin();
    }

    /**
     * 有线程顺序控制的
     *
     * @throws InterruptedException
     */
    private static void countDownLatchExecBusin() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i = 0; i < 6; i++) {
            int threadNum = i + 1;
            new Thread(() -> {
                log.info("线程【{}】执行完毕", threadNum);
                countDownLatch.countDown();
            }).start();
        }
        countDownLatch.await();
        log.info("主线程执行完毕");
    }

    /**
     * 没有线程顺序控制
     */
    private static void exectBusin() {
        for (int i = 0; i < 6; i++) {
            int threadNum = i + 1;
            new Thread(() -> {
                log.info("线程【{}】执行完毕", threadNum);
            }).start();
        }
        log.info("主线程执行完毕");
    }
}
